package com.ruoyi.iot.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.iot.domain.Device;
import com.ruoyi.iot.domain.Product;
import com.ruoyi.iot.domain.emun.DeviceConstant;
import com.ruoyi.iot.mapper.DeviceMapper;
import com.ruoyi.iot.mapper.ProductMapper;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.iot.mapper.CommandMapper;
import com.ruoyi.iot.domain.Command;
import com.ruoyi.iot.service.ICommandService;
import com.ruoyi.iotcommon.constant.RocketTopicConstant;
import com.ruoyi.iotcommon.domain.CommandPostMessage;

/**
 * 指令记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-19
 */
@Slf4j
@Service
public class CommandServiceImpl implements ICommandService {

    @Resource
    private CommandMapper commandMapper;
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private ProductMapper productMapper;

    /**
     * 查询指令记录
     * 
     * @param id 指令记录主键
     * @return 指令记录
     */
    @Override
    public Command selectCommandById(Long id)
    {
        return commandMapper.selectCommandById(id);
    }

    /**
     * 查询指令记录列表
     * 
     * @param command 指令记录
     * @return 指令记录
     */
    @Override
    public List<Command> selectCommandList(Command command)
    {
        return commandMapper.selectCommandList(command);
    }

    /**
     * 新增指令记录
     * 
     * @param command 指令记录
     * @return 结果
     */
    @Override
    public int insertCommand(Command command) {
        return commandMapper.insertCommand(command);
    }

    /**
     * 修改指令记录
     * 
     * @param command 指令记录
     * @return 结果
     */
    @Override
    public int updateCommand(Command command)
    {
        return commandMapper.updateCommand(command);
    }

    /**
     * 批量删除指令记录
     * 
     * @param ids 需要删除的指令记录主键
     * @return 结果
     */
    @Override
    public int deleteCommandByIds(Long[] ids)
    {
        return commandMapper.deleteCommandByIds(ids);
    }

    /**
     * 删除指令记录信息
     * 
     * @param id 指令记录主键
     * @return 结果
     */
    @Override
    public int deleteCommandById(Long id)
    {
        return commandMapper.deleteCommandById(id);
    }

    @Override
    public void sendCommand(String productKey, String channelKey, String deviceKey, String params,String userId,String source) {

        Device device = deviceMapper.selectDeviceByKey(productKey,deviceKey);
        Product product = productMapper.selectProductByKey(productKey);
        String msg = "发送成功";
        int code = 200;
        Command command = new Command();
        command.setProductKey(productKey);
        // 命令id生产规则，时间戳+设备id
        command.setId(System.currentTimeMillis());
        command.setChannelKey(channelKey);
        command.setDeviceKey(deviceKey);
        command.setParams(params);
        command.setPostTime(new Date());
        command.setSource(source);
        command.setUserId(userId==null?0L:Long.parseLong(userId));
        if(device == null){
            msg = "设备不存在";
            code = 500;
            command.setCode(code);
            command.setMessage(msg);
            insertCommand(command);
            return;
        }
        if(!DeviceConstant.STATUS_ONLINE.equals(device.getStatus())){
            msg = "设备不在线";
            code = 500;
            command.setCode(code);
            command.setMessage(msg);
            insertCommand(command);
            return;
        }
        Map<String,Object> paramsMap = null;
        try{
            paramsMap = JSON.parseObject(params,new TypeReference<Map<String, Object>>(){});
        }catch (Exception e){
            log.error("指令参数格式错误",e);
            msg = "指令参数格式错误:"+e.getMessage();
            code = 500;
            command.setCode(code);
            command.setMessage(msg);
            insertCommand(command);
            return;
        }
        try{
            //发送设备指令,发送到不同的网关
            CommandPostMessage commandPostMessage = new CommandPostMessage();
            commandPostMessage.setId(command.getId());
            commandPostMessage.setChannelKey(channelKey);
            commandPostMessage.setProductKey(productKey);
            commandPostMessage.setDeviceKey(deviceKey);
            commandPostMessage.setTime(new Date());
            commandPostMessage.setParams(paramsMap);
            // 同步发送
            rocketMQTemplate.syncSend(RocketTopicConstant.COMMAND_POST+product.getTransformService(),commandPostMessage);
            command.setCode(code);
            command.setMessage(msg);
            insertCommand(command);
        }catch (Exception e){
            log.error("指令发送失败",e);
            msg = "发送失败：:"+e.getMessage();
            code = 500;
            command.setCode(code);
            command.setMessage(msg);
            insertCommand(command);
        }
    }
}
